package my.mark.mybaibaoxiang.eventDemo.spring;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanInitializationException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.UUID;

@Component
public class WarnRuleJob implements ApplicationContextAware {

    private ApplicationContext applicationContext;

    public void myFunction(){
        //通过邮件、短信等发送预警数据.
        sendWarning("我的业务类型", "业务值1","业务值2");
    }

    /**
     * 通过应用上下文发布事件.
     *
     * 该类调用时需在spring上下文里面，比方@Autowired出来，不能直接new，否则获取不到上下文applicationContext。
     *
     * @param type
     * @param target
     * @param content
     */
    public void sendWarning(String type, String target, String content) {
        applicationContext.publishEvent(new WarnEvent(UUID.randomUUID(), type, target, content));
    }

    /**
     * 获取应用上下文：
     * Set the ApplicationContext that this object runs in.
     * Normally this call will be used to initialize the object.
     * <p>Invoked after population of normal bean properties but before an init callback such
     * as {@link InitializingBean#afterPropertiesSet()}
     * or a custom init-method. Invoked after {@link ResourceLoaderAware#setResourceLoader},
     * {@link ApplicationEventPublisherAware#setApplicationEventPublisher} and
     * {@link MessageSourceAware}, if applicable.
     *
     * @param applicationContext the ApplicationContext object to be used by this object
     * @throws ApplicationContextException in case of context initialization errors
     * @throws BeansException              if thrown by application context methods
     * @see BeanInitializationException
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
